// Domain Object
package biz

import (
	"github.com/google/uuid"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var (
	ErrNoShopId = status.Error(codes.InvalidArgument, "shopId invalid")
)

type Item struct {
	ItemId    string
	Name      string
	Desc      string
	Inventory string
	Category  string
	Status    int //是否下架
}

type ShopInventory struct {
	Categorys map[string]int64
	Items     map[string]int64
	Sum       int64
}

type WarehouseDomain struct {
	// dao层
	dao           WarehouseRepo
	ShopId        string //商店id
}

func NewWarehouseDomain(shopId string, repo WarehouseRepo) *WarehouseDomain {

	return &WarehouseDomain{
		dao:    repo,
		ShopId: shopId,
	}
}

func (w WarehouseDomain) GetItemWithId(itemid string) (*Item, error) {
	if w.ShopId == "" {
		return nil , ErrNoShopId
	}

	return w.dao.GetItemWithId(itemid)
}

func (w *WarehouseDomain) GetAllItemsInShop() ([]*Item, error) {
	if w.ShopId == "" {
		return nil, ErrNoShopId
	}

	return w.dao.GetShopItems(w.ShopId)
}

//创建新产品
func (w *WarehouseDomain) OnSaleNewItem(new *Item) (string, error) {
	if w.ShopId == "" {
		return  "", ErrNoShopId
	}

	// 创建新的item
	new.ItemId = uuid.New().String()
	if err := w.dao.CreateItem(new); err != nil {
		return "", err
	}

	// 上架
	if err := w.dao.UpdateItemSaleStatus(new.ItemId, 1); err != nil {
		return "", err
	}

	return new.ItemId, nil
}
